package kr.saeildamil.androidstudty.ch19;

import kr.saeildamil.androidstudty.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

public class AsyncTaskBasic extends Activity {
	TextView tv;
	int mValue;
	ProgressDialog mProgress;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch19_asynctaskbasic);
		tv = (TextView) findViewById(R.id.ch19_asynctask_tv);
		
	}
	
	public void mOnClick(View v){
		new AsyncTaskTest().execute(100);
		
	}
	class AsyncTaskTest extends AsyncTask<Integer, Integer, Integer>{

		@Override
		protected void onPreExecute() {
			Log.d("AsyncTask", "onPreExcute()");
			super.onPreExecute();
			mValue =0;
			mProgress = new ProgressDialog(AsyncTaskBasic.this);
			mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgress.setTitle("Updating");
			mProgress.setMessage("Wait...");
			mProgress.setCancelable(false);
			mProgress.setProgress(0);
			mProgress.setButton(DialogInterface.BUTTON_POSITIVE, "Cancel", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					cancel(true);
				}
			});
			mProgress.show();
		}
		
		@Override
		protected Integer doInBackground(Integer... params) {
			Log.d("AsyncTask", "doInBackground params" + params[0]);
			int i;
			while(!isCancelled()){
				mValue++;
				if(mValue<=100){
					publishProgress(mValue);
				}else{
					break;
				}
				try {Thread.sleep(50);} catch (InterruptedException e) {}
			}
			
			return mValue;
		}
		
		@Override
		protected void onProgressUpdate(Integer... values) {
			Log.d("AsyncTask", "onProgressUpdate Progress" + values[0]);
			super.onProgressUpdate(values);
			mProgress.setProgress(values[0]);
			tv.setText(Integer.toString(values[0]));
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			Log.d("AsyncTask", "onPostExecute Result" + result);
			super.onPostExecute(result);
			mProgress.dismiss();
		}


		@Override
		protected void onCancelled() {
			super.onCancelled();
			mProgress.dismiss();
		}

	}
}
